<template>
  <div>
    <div class="simulator_box">
      <MTabs
        v-model="editableTabsValue"
        :data="editableTabs"
        @handTab="handTab"
      >
        <MtabsItem
          v-for="item in editableTabs"
          :key="item.id"
          :item="item"
        ></MtabsItem>
      </MTabs>
      <!-- <Tabs
        :editableTabs="editableTabs"
        @handAddTab="handAddTab"
        :editableTabsValue.sync="editableTabsValue"
        @handDelete="handDelete"
        @handActive="handActive"
      ></Tabs> -->
      <el-form
        label-position="top"
        :model="form"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="应用程序名称" prop="siddhiAppName">
          <el-select
            filterable
            @change="siddhiSele"
            v-model="form.siddhiAppName"
            placeholder="请选择应用程序名称"
            size="small"
          >
            <el-option
              :label="item.siddhiAppName"
              :value="item.siddhiAppName"
              v-for="item in listSiddhi"
              :key="item.siddhiAppName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="流名称" prop="streamName">
          <el-select
            :disabled="form.listStreams.length == 0"
            filterable
            @change="streamSele"
            v-model="form.streamName"
            placeholder="请选择流名称"
            size="small"
          >
            <el-option
              :label="item.name"
              :value="item.name"
              v-for="item in form.listStreams"
              :key="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间戳">
          <Datepicker
            style="width: 100%"
            v-on:picked="picked"
            v-model="form.timestamp"
          ></Datepicker>
        </el-form-item>
        <el-form-item
          label="属性"
          prop="streamName"
          v-if="form.listAttributes.length !== 0"
        >
          <!-- <div> -->
          <span slot="label" class="str_title"
            >属性
            <img
              @click="handFull"
              src="@/assets/images/full.png"
              class="full_icon"
              alt=""
            />
          </span>
          <!-- </div> -->
          <div class="attr_list">
            <div class="title_box">
              <div class="title">填充属性值</div>
              <div class="sw_box">
                <div class="title">
                  {{ !form.allCheck ? "关闭全部" : "打开全部" }}
                </div>
                <el-switch v-model="form.allCheck" @change="handAll">
                </el-switch>
              </div>
            </div>
            <el-form-item
              class="attr_value"
              v-for="(item, index) in form.listAttributes"
              :key="item.name"
              :prop="'listAttributes.' + index + '.value'"
              :rules="[
                {
                  required: !item.isCheck,
                  message: item.name + '不能为空',
                  trigger: 'blur',
                },
                {
                  validator(rule, value, callback) {
                    validatorForm(rule, value, callback, item);
                  },
                  trigger: 'blur',
                },
              ]"
            >
              <div class="a_title">{{ item.name }} ({{ item.type[0] }})</div>
              <div class="a_input">
                <el-input
                  style="width: 100%; margin-right: 4px"
                  v-model="item.value"
                  placeholder="请输入"
                  size="small"
                  :disabled="item.isCheck"
                  clearable
                ></el-input>
                <el-switch v-model="item.isCheck" @change="item.value = ''">
                </el-switch>
              </div>
            </el-form-item>
            <!-- <div></div> -->
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="btns_box">
      <el-button
        size="small"
        v-if="form.siddhiState"
        style="width: 50%"
        :type="form.siddhiState == 'RUN' ? 'success' : 'danger'"
        plain
        >程序状态:{{ form.siddhiState }}</el-button
      >
      <el-button
        :disabled="this.form.siddhiState == 'FAULTY'"
        style="width: 50%"
        type="primary"
        size="small"
        @click="sumbitRun"
        :loading="btnLoading"
      >
        {{ form.siddhiState == "STOP" ? "启动并发送" : "发送" }}
      </el-button>
      <!-- <el-button style="width: 50%" type="primary" @click="edgeStopApp">
        关闭
      </el-button> -->
    </div>
    <AttrDw ref="attrDw" :cloneAttr="cloneAttr" @sumbit="sumbit"></AttrDw>
  </div>
</template>

<script>
import _ from "lodash";
import { generateId } from "@/utils/index";
import MtabsItem from "./MtabsItem.vue";
import MTabs from "./MTabs.vue";
import { mapGetters } from "vuex";
import {
  listStreams,
  listAttributes,
  edgeRunApp,
  single,
  // edgeStopApp,
} from "@/api/siddhi";
import { valiType } from "@/views/edge/inputSourcePage/js/index";
import AttrDw from "./AttrDw.vue";
import Datepicker from "@/components/Datepicker";
export default {
  components: {
    MtabsItem,
    MTabs,
    AttrDw,
    Datepicker,
  },
  computed: {
    ...mapGetters(["listSiddhiApps"]),
    listSiddhi() {
      return this.listSiddhiApps;
    },
    validatorForm() {
      return function (rule, value, callback, item) {
        // 如果没选中,直接返回
        if (item.isCheck === true) {
          callback();
        }
        const msg = valiType(value, item.type);

        if (msg.length === 0) {
          callback();
        } else {
          callback(new Error(msg));
        }
      };
    },
  },
  data() {
    return {
      btnLoading: false,
      form: {
        siddhiState: "",
        siddhiAppName: "",
        streamName: "",
        listAttributes: [],
        allCheck: false,
        timestamp: "",
        listStreams: [],
      },
      value1: false,
      rules: {
        siddhiAppName: [
          { required: true, message: "请选择应用程序名称", trigger: "change" },
        ],
        streamName: [
          { required: true, message: "请选择流名称", trigger: "change" },
        ],
      },
      tabIndex: 0,
      editableTabs: [
        {
          conditionId: "S1",
          id: "1",
          form: {
            siddhiState: "",
            timestamp: "",
            siddhiAppName: "",
            streamName: "",
            listAttributes: [],
            allCheck: false,
            listStreams: [],
          },
        },
      ],
      editableTabsValue: "1",
      cloneAttr: [],
    };
  },
  mounted() {
    this.editableTabs[0].form = this.form;
  },
  methods: {
    picked(date) {
      // this.form.timestamp = _.toString(date);
      console.log(`你选择了${this.form.timestamp}`);
    },
    handFocus() {},
    handedgeRunApp() {},
    sumbitRun() {
      // this.$refs.ceshi.focus();
      this.$refs["ruleForm"].validate(async (valid) => {
        if (valid) {
          if (this.form.siddhiState == "FAULTY") {
            return;
          }
          this.btnLoading = true;
          if (this.form.siddhiState == "RUN") {
            this.form.data = this.form.listAttributes.map((item) => {
              item.value = item.value == "" ? null : item.value;
              return item.value;
            });
            try {
              const res = await single(this.form);
              this.$msg({
                type: "success",
                message: "发送成功",
              });
              this.$store.dispatch("siddhi/setLogData", {
                message: this.form.siddhiAppName + "发送成功!",
                type: "INFO",
              });
              this.$store.dispatch("siddhi/setConsoleState", true);
              this.btnLoading = false;
            } catch (error) {
              this.$store.dispatch("siddhi/setLogData", {
                message: this.form.siddhiAppName + "发送失败!",
                type: "ERROR",
              });
              this.$store.dispatch("siddhi/setConsoleState", true);
              this.btnLoading = false;
            }
          } else {
            edgeRunApp(
              JSON.stringify({
                siddhiAppName: this.form.siddhiAppName,
                variables: {},
              })
            )
              .then(async (res) => {
                try {
                  let resName = res.data.runtimeId;
                  this.$store.dispatch("siddhi/setLogData", {
                    message: resName + " 启动成功!",
                    type: "INFO",
                  });
                  console.log(res, "启动成功");
                  this.form.siddhiState = "RUN";
                  // 从新从vuex里拉取siddhi列表(更新状态)
                  await this.$store.dispatch("siddhi/getListSiddhi", data);
                  this.$store.dispatch("siddhi/setConsoleState", true);
                  this.btnLoading = false;
                } catch (error) {
                  this.btnLoading = false;
                }
              })
              .catch((Error) => {
                if (Error.response != undefined) {
                  this.btnLoading = false;
                  this.$store.dispatch("siddhi/setLogData", {
                    message: Error.response.data,
                    type: "ERROR",
                  });
                  this.$store.dispatch("siddhi/setConsoleState", true);
                }
              });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    sumbit(arr) {
      this.form.listAttributes = arr;
    },
    handAll() {
      this.form.listAttributes = this.form.listAttributes.map((item) => {
        return {
          ...item,
          value: "",
          isCheck: this.form.allCheck,
        };
      });
    },
    handFull() {
      // this.cloneAttr = _.cloneDeep(this.form.listAttributes);
      this.$nextTick(() => {
        this.$refs.attrDw.cloneAttr = _.cloneDeep(this.form.listAttributes);
        this.$refs.attrDw.drawer = true;
      });
    },
    // 获取流下的属性
    streamSele(val) {
      listAttributes({
        siddhiAppName: this.form.siddhiAppName,
        streamName: val,
      }).then((res) => {
        console.log(res);
        const { data } = res;
        this.form.listAttributes = data.map((item) => {
          return {
            ...item,
            isCheck: false,
            value: "",
            type: [item.type],
          };
        });
      });
    },
    // edgeStopApp() {
    //   edgeStopApp("未命名12333");
    // },
    // 获取流
    siddhiSele(val) {
      // 从vuex获取流
      this.form.siddhiState = this.$store.getters["siddhi/getsiddhiFlow"](val);
      // this.form.siddhiState = this.listSiddhi.find(
      //   (item) => item.siddhiAppName == val
      // ).mode;
      if (!val) {
        return;
      }

      listStreams(val).then((res) => {
        const { data } = res;
        this.form.streamName = "";
        this.form.listAttributes = [];
        this.form.listStreams = data.map((item) => {
          return {
            name: item,
          };
        });
      });
    },
    clearValidate(formName = "ruleForm") {
      this.$nextTick(() => {
        this.$refs[formName].clearValidate();
      });
    },
    handActive(item) {
      this.form = item.form;
      this.editableTabsValue = item.id;
      this.clearValidate();
      console.log(this.form);
    },
    handTab(type, item) {
      if (type == "add") {
        this.handAddTab();
      }
      if (type == "del") {
        this.handDelete(item.id);
      }
      if (type == "click") {
        this.handActive(item);
      }
    },
    handDelete(id) {
      // 留最后一个
      if (this.editableTabs.length <= 1) {
        return;
      }
      let tabs = this.editableTabs;
      this.editableTabs = tabs.filter((tab) => tab.id !== id);
      const item = this.editableTabs[this.editableTabs.length - 1];
      console.log("item", item);
      this.editableTabsValue = item.id;
      // this.$set(this, "editableTabsValue", item.id);
      this.form = item.form;
      this.clearValidate();
    },
    handAddTab() {
      let newTabName = "S" + ++this.tabIndex;
      this.editableTabs.forEach((item) => {
        if (item.conditionId == newTabName) {
          newTabName = "S" + ++this.tabIndex;
        }
      });
      this.editableTabs.push({
        conditionId: newTabName,
        id: generateId(),
        form: {
          siddhiAppName: "",
          streamName: "",
          listAttributes: [],
          listStreams: [],
          allCheck: false,
          siddhiState: "",
          timestamp: "",
        },
      });
      const item = this.editableTabs[this.editableTabs.length - 1];
      this.editableTabsValue = item.id;
      // this.form.listStreams = [];
      this.form = item.form;
      this.form.timestamp = "";
      this.clearValidate();
    },
  },
};
</script>

<style lang='scss' scoped>
.simulator_box {
  height: calc(100vh - 145px - 100px - 30px) !important;
  overflow: auto;
  padding: 0 10px;
}
.str_title {
  /* width: 100%; */
  /* position: relative; */
  .full_icon {
    cursor: pointer;
    position: absolute;
    right: 0;
    top: 50%;
    margin-top: -5px;
    width: 10px;
    height: 10px;
  }
}
.btns_box {
  padding: 0 10px;
  display: flex;
  justify-content: center;

  align-items: center;
  flex-wrap: nowrap;
}
.attr_list {
  max-height: 120px;
  overflow: auto;
}
.attr_value {
  display: flex;
  flex-direction: column;
  /* margin-top: 16px; */
  width: 100%;
  /deep/ .el-form-item__content {
    line-height: 24px;
  }
  .a_input {
    display: flex;
    align-items: center;
  }
  .a_title {
    color: #666666;
    font-size: 12px;
    /* margin-bottom: 4px; */
  }
}
/deep/ .el-switch__core::before {
  content: "否";
  position: absolute;
  top: 0;
  right: 5px;
  color: #fff;
}
.is-checked /deep/ .el-switch__core::before {
  content: "是";
  position: absolute;
  top: 0;
  left: 5px;
  color: #fff;
}
.attr_list {
  background-color: #e9e9e9;
  padding: 10px;

  .title_box {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .sw_box {
      display: flex;
      align-items: center;
      .title {
        color: #333;
        margin-right: 10px;
      }
    }
    .title {
      color: #333333;
      font-size: 13px;
    }
  }
}
/deep/ .el-form-item {
  margin-bottom: 0;
}
/deep/ .el-form-item__label {
  width: 100%;
  padding-bottom: 0;
  position: relative;
}
/deep/ .el-select {
  width: 100%;
}
</style>